/*******************************************************************************************
Copyright (C) 2016 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*******************************************************************************************/

/*globals FileDialog, settings, Dir, Application, NMRSpectrum, varianExpName, brukerExpName, print, File, TextStream, MnUi*/
/*jslint plusplus: true, indent: 4*/

function exportGSD() {
	"use strict";
	var dw, pageCount, i, page, itemCount, j, spec, l, peaks, n, path, expname, slashIndex, filename,
		fout, sout, MHz, points, sw, k, peak, area,
		dirSettingsKey = "exportGSD/LastDir",
		dirName = FileDialog.getExistingDirectory(settings.value(dirSettingsKey, Dir.home()));
	if (!dirName.length) {
		return;
	}
	settings.setValue(dirSettingsKey, dirName);

	dw = Application.mainWindow.activeWindow();
	pageCount = dw.pageCount();
	for (i = 0; i < pageCount; i++) {
		page = dw.page(i);
		itemCount = page.itemCount();
		for (j = 0; j < itemCount; j++) {
			spec = new NMRSpectrum(page.item(j));
			if (spec.isValid() && spec.dimCount === 1) { // if page item is a 1D spectrum
				for (l = 0; l < spec.specCount; l++) {
					spec.curSpecIndex = l;
					peaks = spec.peaks();
					n = peaks.count;
					path = spec.getParam("Data File Name");
					if (!path.length) {
						return;
					}
					expname = "";
					if (spec.originalFormat === "Varian") {
						expname = varianExpName(path);
					} else if (spec.originalFormat === "Bruker XWIN-NMR") {
						expname = brukerExpName(path);
					} else {
						slashIndex = Math.max(path.lastIndexOf("\\"), path.lastIndexOf("/"));
						if (slashIndex === -1) {
							expname = path;
						} else {
							expname = path.slice(slashIndex + 1, path.last);
						}
					}
					expname = expname.replace(/\//g, "_");
					if (spec.specCount > 1) {
						expname += "-" + (l + 1).toString();
					}
					filename = dirName + "/" + expname + ".txt";
					print(filename);
					fout = new File(filename);
					fout.open(File.WriteOnly);
					sout = new TextStream(fout);
					sout.precision = 10;

					freq = spec.frequency(1);
					points = spec.count(1);
					sw = spec.scaleWidth(1);
					for (k = 0; k < n; k++) {
						peak = peaks.at(k);
						sout.write(peak.delta(), "\t", peak.intensity, "\t", peak.width() * freq, "\t", peak.integralInPts(spec), "\n");
					}
					fout.close();
				}
			}
		}
	}
}

if (this.MnUi && MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_ExportGSDSpectra = exportGSD;
}
